import React, { Component } from 'react'
import { Form, Button, Table, Row, Col, Popconfirm, Icon, Modal, Input, Checkbox } from 'antd';
import * as fetch from '../../utils/http'


class DeviceList extends Component {
    constructor(props) {
        super(props)
        this.state = {
            visibleDeviceModal: false,
            visibleChildModal: false,
            currentDevie: {},
            deviceList: [],
            selectedRowKeys: [],
            deviceChildList: []
        }
        this.getAllDevice()
        this.getAllChild()
    }

    getAllDevice() {
        fetch.get('Device/GetDevices').then(res => {
            this.setState({
                deviceList: res.data || []
            })
        })
    }

    getAllChild() {
        fetch.get('DeviceItem/GetDeviceItems').then(res => {
            this.setState({
                deviceChildList: res.data || []
            })
        })
    }

    newDevice() {
        this.setState({
            visibleDeviceModal: true
        })
    }

    onEditDevice(item) {
        this.setState({
            currentDevie: item,
            visibleDeviceModal: true
        })
    }

    onDelDevice(item) {
        const { id } = item
        fetch.post('Device/Delete', { id }).then(res => {
            this.getAllDevice()
        })
    }

    addChildToDevice(currentDevie) {
        this.setState({
            currentDevie,
            visibleChildModal: true,
            selectedRowKeys: currentDevie.deviceItems.map(item => item.id)
        })
    }

    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys }, () => {
            console.log(this.state.selectedRowKeys)
        });
    }

    saveChildToDevice() {
        const { selectedRowKeys, currentDevie } = this.state
        const params = {
            deviceID: currentDevie.id,
            deviceItemIDs: selectedRowKeys
        }
        fetch.post('Device/RelatedDeviceDeviceItem', params).then(res => {
            this.setState({
                visibleChildModal: false
            })
            this.getAllDevice()
        })
    }

    addChild = () => {
        const item = this.state.currentDevie
        const AddChildModal = Form.create()(props => {
            const { form } = props
            const { getFieldDecorator } = form;

            const onSaveDevice = () => {
                form.validateFields((err, values) => {
                    if (!err) {
                        this.setState({
                            visibleChildModal: false
                        })
                        const params = values
                        if (item.id) {
                            fetch.post('Device/Edit', params).then(res => {
                                this.getAllDevice()
                            })
                        } else {
                            fetch.post('Device/Add', params).then(res => {
                                this.getAllDevice()
                            })
                        }
                        this.setState({
                            visibleDeviceModal: false,
                            currentDevie: {}
                        })
                    }
                })
            }

            const cancelModal = () => {
                form.resetFields()
                this.setState({
                    currentDevie: {},
                    visibleDeviceModal: false
                })
            }

            return (
                < Modal title='设备详情'
                    cancelText='取消'
                    onCancel={cancelModal}
                    onOk={onSaveDevice}
                    okText='确定'
                    visible={this.state.visibleDeviceModal}
                >
                    <Form className="login-form">
                        <Form.Item label="id" className="hidden-input">
                            {getFieldDecorator('id', {
                                initialValue: item.id
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder=""
                                />,
                            )}
                        </Form.Item>
                        <Form.Item label="设备名" >
                            {getFieldDecorator('name', {
                                initialValue: item.name
                            })(
                                <Input
                                    className="h-40"
                                    type="text"
                                    placeholder="设备名"
                                />
                            )}
                        </Form.Item>
                    </Form>
                </ Modal>
            )
        })
        return <AddChildModal />
    }

    render() {
        const { deviceList, selectedRowKeys, deviceChildList } = this.state
        const columns = [
            {
                title: '设备名称',
                dataIndex: 'name',
                key: 'name'
            },
            {
                title: '设备子项',
                render: item => (
                    <div onClick={this.addChildToDevice.bind(this, item)} style={{ fontSize: '14px', cursor: 'pointer' }}>
                        <Icon type="plus-square" style={{ marginRight: '5px' }}></Icon>
                        {
                            item.deviceItems.length ?
                                item.deviceItems.map((child, index) => {
                                    return (
                                        <span key={index}>{child.itemName}{index === item.deviceItems.length - 1 ? '' : '、'}</span>
                                    )
                                })
                                :
                                ''
                        }
                    </div>
                )
            },
            {
                title: '操作',
                width: 100,
                render: item => (
                    <Row type="flex" justify="space-between">
                        <Col>
                            <Button type="primary" size="small" onClick={this.onEditDevice.bind(this, item)} icon="form"></Button>
                        </Col>
                        <Col>
                            <Popconfirm
                                onConfirm={this.onDelDevice.bind(this, item)}
                                title="确定删除吗？"
                                okText="删除"
                                cancelText="取消"
                                icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                            >
                                <Button type="danger" size="small" icon="delete"></Button>
                            </Popconfirm>
                        </Col>
                    </Row>
                )
            }
        ]

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };

        const childColumns = [
            {
                title: '设备子项',
                key: 'itemName',
                dataIndex: 'itemName',
            },
        ]

        return (
            <div>
                <h3>设备管理 - 设备列表</h3>
                <Button type="primary" onClick={this.newDevice.bind(this)}>新增设备</Button>
                <div style={{ padding: '10px 0px' }}>
                    <Table dataSource={deviceList} bordered columns={columns} rowKey="id" pagination={false}></Table>
                </div>
                <Modal
                    cancelText='取消'
                    okText='确定'
                    title='设备详情'
                    onOk={this.saveChildToDevice.bind(this)}
                    onCancel={() => {
                        this.setState({
                            visibleChildModal: false
                        })
                    }}
                    visible={this.state.visibleChildModal}>
                    {
                        this.state.showErrorMsg ?
                            <p style={{ color: 'red' }}>请检查已选的信号，是否正确填写标签</p> :
                            ''
                    }
                    <Table bordered rowSelection={rowSelection} dataSource={deviceChildList} columns={childColumns} rowKey="itemID" pagination={false}></Table>
                </Modal>

                {this.addChild()}
            </div>
        );
    }
}

export default DeviceList;